package com.rran.study.chat.ops.service.accept;

import com.alibaba.fastjson.JSON;
import com.rran.study.chat.ops.pojo.socketmsg.MessageContext;
import com.rran.study.chat.ops.pojo.socketmsg.SingleMsg;
import com.rran.study.chat.ops.enums.MessageType;
import com.rran.study.chat.ops.repository.ChannelFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author yy
 * @Type SingleAcceptStrategyHandler.java
 * @Desc 一对一消息发送
 * @date 2020/8/7 10:55
 */
@AcceptHandler(messageType = MessageType.SINGLE)
@Component
@Slf4j
public class SingleAcceptStrategyHandler extends AbstractAcceptStrategy<SingleMsg> {

    @Override
    protected void doAccept(MessageContext<SingleMsg> context) {
        SingleMsg singleMsg = context.getChatMessage();
        String target = singleMsg.getTarget();
        ChannelHandlerContext ctx = getTargetChannel(target);
        try{
            ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(singleMsg)));
        }catch (NullPointerException e){
            log.info(target + "用户下线了，发送失败");
        }catch (Exception e){
            log.error("socket异常：{}",e.getMessage());
        }
    }

    private ChannelHandlerContext getTargetChannel(String target) {
        return ChannelFactory.getChannelHandlerContext(target);
    }
}
